// pages/editUser/editUser.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: "https://head.image.jiajijie.com/dj/",
    pictureUrl:'/image/',
    positive: "/image/zm@2x.png", //正
    negative: "/image/fan@2x.png",
    positive_normal:"",
    negative_normal:"",
    cityArray: ["城镇户口", "农业户口"],
    index: 1,
    uname: "", //姓名
    cardId: "", //身份证号
    tel: "", //手机号码
    accountFlag: false,
    unameFlag: false,
    telFlag: false,
    cardIdFlag: false,
    censusFlag: true,
    idCardFlag:false
  },
  chooseCity(){
    this.setData({
      index:1
    })
  },
  chooseCountryside(){
    this.setData({
      index:2
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let url=app.globalData.url
    if(options.id){
      this.setData({
        id:options.id
      })
      wx.showLoading({
        title: '等待中',
        mask: true
      })
      app.request("daijiao/insured_person/edit",{ipid:options.id},true).then(res=>{
        wx.hideLoading()
        if(res.error_code==0){
          console.dir(res.data)
          this.setData({
            index:res.data.census_type,
            cardId:res.data.id_card,
            uname:res.data.name,
            positive: app.globalData.url.substring(0,app.globalData.url.length-4) + res.data.id_card_positive,
            negative: app.globalData.url.substring(0, app.globalData.url.length - 4) + res.data.id_card_back,
            positive_normal: res.data.id_card_positive,
            negative_normal: res.data.id_card_back,
            tel:res.data.mobile
          })
        }
      })
    }
  },
  // 上传正面证件
  updatePositive() {
    let that = this;
        wx.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: function (res) {
            if (res.tempFiles[0].size >= 2000000){
              wx.showModal({
                content: '上传失败，图片大小限制在2M内',
                showCancel: false
              })
            }else{
              that.setData({
                positive: res.tempFilePaths[0],//当前展示
              })
              wx.showLoading({
                title: '等待中',
                mask:true
              })
              wx.uploadFile({
                url: app.globalData.url+'upload',
                filePath: res.tempFilePaths[0],
                name: 'file',
                header: {
                  "content-type": "multipart/form-data"
                },
                success(resData) {
                  let resDatas = JSON.parse(resData.data)
                  if (resDatas.error_code == 0) {
                    wx.hideLoading()
                    that.setData({
                      uname: resDatas.data.name,
                      cardId: resDatas.data.idcard,
                      positive_normal: resDatas.data.url,//上传到服务器
                    })
                  }
                },
                fail(err) {
                  wx.hideLoading()
                  wx.showModal({
                    content: '图片上传失败，请重试',
                    showCancel: false
                  })
                },
              })
            }
          },
          fail: function (err) {
          }
        })

  },
  // 上传反面证件
  updateNegative() {
    let that = this;
    // wx.showActionSheet({
    //   itemList: ['拍照', '从手机相册选择'],
    //   success(res) {
    //     if (res.tapIndex == 0) {

    //     } else if (res.tapIndex == 1) {
          wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: function(res) {
              console.warn(res)
              if (res.tempFiles[0].size >= 2000000){
                wx.showModal({
                  content: '上传失败，图片大小限制在2M内',
                  showCancel: false
                })
              }else{
                that.setData({
                  negative: res.tempFilePaths[0],//当前展示
                })
                wx.uploadFile({
                  url: app.globalData.url + 'upload',
                  filePath: res.tempFilePaths[0],
                  name: 'file',
                  header: {
                    "content-type": "multipart/form-data"
                  },
                  success(resData) {
                    if (resData.statusCode==413 ){
                      wx.showModal({
                        content: '图片上传失败，请重试',
                        showCancel: false
                      })
                    }
                    let resDatas = JSON.parse(resData.data)
                    if (resDatas.error_code == 0) {
                      that.setData({
                        negative_normal: resDatas.data.url,//上传到服务器
                      })
                    }
                  },
                  fail(err){
                    wx.showModal({
                      content: '图片上传失败，请重试',
                      showCancel:false
                    })
                  },
                })
              }
            },
            fail: function(err) {
              // wx.showModal({
              //   content: '上传失败，图片大小限制在2M内',
              //   showCancel: false
              // })
            }
          })
    //     }
    //   }
    // })
  },
  closeDialog(){
    this.setData({
      idCardFlag:false
    })
  },  
  // 保存
  save() {
    let flag = true;
    let that = this;
    // positive_normal:"",
    // negative_normal:"",
    if(!this.data.positive_normal || !this.data.negative_normal){
      this.setData({
        idCardFlag:true
      })
      return
    }
    if(this.data.uname.length<2 || this.data.uname==""){
      this.setData({
        unameFlag:true
      })
      flag=false
      return
    }else{
      this.setData({
        unameFlag: false
      })
      flag = true
    }

    if(this.isCardID(this.data.cardId) != true){
      this.setData({
        cardIdFlag:true
      })
      flag = false
      return
    }else{
      this.setData({
        cardIdFlag: false
      })
      flag = true
    }

    if(this.data.index===""){
      this.setData({
        accountFlag:true
      })
      flag= false
      return 
    }else{
      this.setData({
        accountFlag:false
      })
      flag=true
    }

    if(this.data.tel.length!=11){
      this.setData({
        telFlag:true
      })
      flag=false
      return
    }else{
      this.setData({
        telFlag:false
      })
      flag = true
    }

    if (flag) {
      wx.showLoading({
        title: '等待中',
        mask:true
      })  
      let msg = {
        name: that.data.uname,
        id_card: that.data.cardId,
        id_card_positive:that.data.positive_normal,
        id_card_back: that.data.negative_normal,
        mobile: that.data.tel,
        census_type: that.data.index
      }
      if(that.data.id){
        msg.ipid=that.data.id
        app.request('daijiao/insured_person/update', msg, true).then(res => {
          wx.hideLoading()
          if (res.error_code == 0) {
            wx.showToast({
              title: '成功',
              mask: true,
              duration: 1000,
              success() {
                wx.navigateBack({
                })
              }
            })
          }else{
            wx.showModal({
              content: res.error_message,
              showCancel:false
            })
          }
        })
      }else{
        app.request('daijiao/insured_person/store', msg, true).then(res => {
          wx.hideLoading()
          if (res.error_code == 0) {
            wx.showToast({
              title: '成功',
              mask: true,
              duration: 1000,
              success() {
                wx.navigateBack({
                })
              }
            })
          }else{
            wx.showModal({
              content: res.error_message,
              showCancel:false
            })
          }
        })
      }
      }

  },
  // 选择公积金比例
  bindPickerChange(e) {
    this.setData({
      index: e.detail.value
    })
  },
  // 手机号输入
  telInput(e) {
    this.setData({
      tel: e.detail.value.replace(/\D/g, '')
    })
  },
  // 身份证号输入
  cardInput(e) {
    this.setData({
      cardId: e.detail.value.replace(/\s/g, "")
    })
  },
  // 姓名输入
  usernameInput(e) {
    this.setData({
      uname: e.detail.value.replace(/\s/g, "")
    })
  },

  // 身份证号验证
  isCardID(sId) {
    var aCity = {
      11: "北京",
      12: "天津",
      13: "河北",
      14: "山西",
      15: "内蒙古",
      21: "辽宁",
      22: "吉林",
      23: "黑龙江",
      31: "上海",
      32: "江苏",
      33: "浙江",
      34: "安徽",
      35: "福建",
      36: "江西",
      37: "山东",
      41: "河南",
      42: "湖北",
      43: "湖南",
      44: "广东",
      45: "广西",
      46: "海南",
      50: "重庆",
      51: "四川",
      52: "贵州",
      53: "云南",
      54: "西藏",
      61: "陕西",
      62: "甘肃",
      63: "青海",
      64: "宁夏",
      65: "新疆",
      71: "台湾",
      81: "香港",
      82: "澳门",
      91: "国外"
    };
    var iSum = 0;
    var info = "";
    // /^\d{17}(\d|x)$/i
    var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (!/^\d{17}(\d|x)$/i.test(sId)) return "请输入15或18位正确身份证号";
    sId = sId.replace(/x$/i, "a");
    if (aCity[parseInt(sId.substr(0, 2))] == null)
      return "请输入15或18位正确身份证号";
    let sBirthday =
      sId.substr(6, 4) +
      "-" +
      Number(sId.substr(10, 2)) +
      "-" +
      Number(sId.substr(12, 2));
    var d = new Date(sBirthday.replace(/-/g, "/"));
    if (
      sBirthday !=
      d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()
    )
      return "请输入15或18位正确身份证号";
    for (var i = 17; i >= 0; i--)
      iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
    if (iSum % 11 != 1) return "请输入15或18位正确身份证号";
    return true;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      title: "社保/公积金代缴、公积金提取!",
      path: '/pages/home/home',
      imageUrl: 'https://head.image.jiajijie.com/dj/images/fiveshareBg.png',
      success: function (res) {
      },
      fail: function (res) {
        console.log(res)
      }
    }
  }
})